package com.jsg.sl651.enums;

import com.jsg.sl651.util.ByteUtil;
import lombok.AllArgsConstructor;
import lombok.Getter;

/**
 * 控制字符定义
 */
@AllArgsConstructor
@Getter
public enum ControlCharacterDefinition {
    SOH("帧起始", "帧起始", "7E7E", "01"),
    STX("报文传输正文起始","报文传输正文起始","02",null),
    SYN("多包传输正文起始","多包发送，一次确认的传输模式中使用","16",null),
    ETX("报文传输正文结束","作为报文结束符，表示传输完成，等待退出通信","03",null),
    ETB("报文结束，后续还有报文","在报文分包传输时作为报文结束符，表示数据未传输完整，不可退出通信","17",null),
    ENQ("询问","作为下行查询及控制命令帧的报文结束符","05",null),
    EOT("传输结束，退出","作为传输结束确认帧报文结束符，表示可以退出通信","04",null),
    ACK("肯定确认，继续发送","作为有后续报文的“确认帧”报文结束符","06",null),
    NAK("否认应答，反馈重发","用于要求对方重新发送数据包的报文结束符","15",null),
    ESC("传输结束，终端保持在线","在下行确认帧代替EOT作为报文结束符，要求终端在线，保持在线10分钟如果10分钟内没有收到中心站命令，终端退回原先设定的工作状态","1B",null),
    UNKNOWN("未知","未知","00",null),


    ;
    private final String function;
    private final String desc;
    private final String hex;
    private final String asciiHex;


    public String getMessageHex() {
        return getMessageHex(CommunicationMessageType.HEX);
    }

    public String getMessageHex(CommunicationMessageType type) {
        if (type == CommunicationMessageType.HEX || asciiHex == null) {
            return hex;
        } else {
            return asciiHex;
        }
    }

    public byte[] getMessageBytes(CommunicationMessageType type) {
        if (type == CommunicationMessageType.HEX || asciiHex == null) {
            return ByteUtil.toBytes(hex);
        } else {
            return ByteUtil.toBytes(asciiHex);
        }
    }

    public static ControlCharacterDefinition getControlCharacterDefinition(CommunicationMessageType type,String hex) {
        for (ControlCharacterDefinition controlCharacterDefinition : ControlCharacterDefinition.values()) {
            if (type == CommunicationMessageType.HEX) {
                if (controlCharacterDefinition.getHex().equals(hex)) {
                    return controlCharacterDefinition;
                }
            } else {
                if (controlCharacterDefinition.getAsciiHex().equals(hex)) {
                    return controlCharacterDefinition;
                }
            }
        }
        return UNKNOWN;
    }

}
